package com.itheima.app.mapper;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.LocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MakeFriendManager {

    @Reference
    private RecommendUserService recommendUserService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
     private VisitorService visitorService;

    @Reference
    private QuestionService questionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private FriendService friendService;

    @Reference
    private LocationService locationService;

    //查找推荐给我的缘分值最高的用户
    public RecommendUserVo findTodayBest() {
        //1. 获取登录用户id
        Long userId = UserHolder.getUser().getId();

        //2. 调用service根据登录用户id查询推荐给我的缘分值最高的用户
        RecommendUser recommendUser = recommendUserService.findMaxScoreByUserId(userId);
        if (recommendUser == null) {//推荐表中未给当前登录用户推荐数据,手动推荐1号用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setToUserId(userId);
            recommendUser.setScore(100D);
        }

        //3. 根据推荐用户的id查询其详情
        Long uid = recommendUser.getUserId();//推荐给你的
        UserInfo userInfo = userInfoService.findById(uid);

        //4. 组装返回数据
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfo);//推荐用户详情
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());//二者缘分值

        return recommendUserVo;
    }

    //推荐用户列表
    public PageBeanVo findRecommendUser(Integer pageNum, Integer pageSize) {
        //1. 获取登录用户id
        Long userId = UserHolder.getUser().getId();

        //2. 调用service分页查询推荐用户列表
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUser(userId, pageNum, pageSize);
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();

        //如果查询不到推荐数据,手动推荐2-11号数据给当前登录用户
        if (CollectionUtil.isEmpty(recommendUserList)) {
            for (long i = 2; i <= 11; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(i);
                recommendUser.setToUserId(userId);
                recommendUser.setScore(RandomUtil.randomDouble(80, 100));
                recommendUserList.add(recommendUser);
            }
        }

        //3. 组装返回数据
        List<RecommendUserVo> recommendUserVoList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            //3-1. 根据推荐用户的id查询其详情
            Long uid = recommendUser.getUserId();//推荐给你的
            UserInfo userInfo = userInfoService.findById(uid);

            //3-2. 组装返回数据
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            recommendUserVo.setUserInfo(userInfo);//推荐用户详情
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());//二者缘分值

            recommendUserVoList.add(recommendUserVo);
        }

        pageBeanVo.setItems(recommendUserVoList);

        return pageBeanVo;
    }

    //查询佳人信息userinfo + 缘分值
    public RecommendUserVo findPersonalInfo(Long id) {
        //1. 查询佳人的用户信息
        UserInfo userInfo = userInfoService.findById(id);

        //2. 获取登录用户id
        Long userId = UserHolder.getUser().getId();

        //3. 根据两个id获取推荐用户信息(缘分值)
        RecommendUser recommendUser = recommendUserService.findByuserIdAndToUserId(userId, id);

        //4. 组装返回数据
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());
        return recommendUserVo;
    }

    //查询访客列表
    public List<VisitorVo> findVisitor() {
        //1. 获取登录用户id
        Long userId = UserHolder.getUser().getId();

        //2.从redis中查询当前用户的最后一次访问时间
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        //如果查不到
        if (StringUtils.isEmpty(lastAccessTime)) {
            lastAccessTime = System.currentTimeMillis() + "";
        }

        //3. 调用service查询访客列表
        List<Visitor> visitorList = visitorService.findVisitorList(userId, lastAccessTime);
        List<VisitorVo> visitorVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(visitorList)) {
            for (Visitor visitor : visitorList) {
                //1. 查询访客的详细信息
                UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());

                //2. 组装vo
                VisitorVo visitorVo = new VisitorVo();
                visitorVo.setUserInfo(userInfo);
                visitorVo.setFateValue(visitor.getScore().longValue());

                //3. 存储vo
                visitorVoList.add(visitorVo);
            }
        }

        //4. 更新redis中的最后一次访问时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");
        System.out.println(visitorVoList);
        return visitorVoList;
    }

    //查看陌生人问题
    public String findStrangerQuestions(Long userId) {
        //1. 调用service查询
        Question question = questionService.findByUserId(userId);

        //2. 如果查询不到,设置默认问题
        String strangerQuestion = "";
        if (question == null) {
            strangerQuestion = "你是喜欢吃苹果还是香蕉?";
        }else{
            strangerQuestion = question.getStrangerQuestion();
        }
        //3. 返回结果
        return strangerQuestion;
    }

    //打招呼
    public void replyStrangerQuestion(long strangerId, String reply) {
        //获取登录id
        Long userId = UserHolder.getUser().getId();

        //获取登录用户昵称
        UserInfo userInfo = userInfoService.findById(userId);

        //查询陌生人问题
        Question question = questionService.findByUserId(strangerId);
        //设置默认问题；
        String strangerQuestion="你是喜欢吃苹果还是梨？";
        if(question!=null){
            //如果问题不为空，采用设置好的问题
            strangerQuestion=question.getStrangerQuestion();
        }
        //组装成map--->json

        HashMap<String,String> map=new HashMap<>();
        map.put("userId",userId+"");//用户id
        map.put("nickname",userInfo.getNickname());//陌生人昵称
        map.put("strangerQuestion",strangerQuestion);//陌生人问题
        map.put("reply",reply);//问题回复
        String json= JSON.toJSONString(map);

        //调用环信的方法发送消息
        huanXinTemplate.sendMsg(strangerId+"",json);
    }

    //添加好友
    public void addContacts(long friendId) {
         // 获取登录人id
        Long userId = UserHolder.getUser().getId();

        //调用service向mongo中保存好友关系
        friendService.addContacts(userId,friendId);

        //调用template向环信中保存好友关系
        huanXinTemplate.addContacts(userId,friendId);
    }

    //分页查询我的所有好友
    public PageBeanVo findContact(Integer pageNum, Integer pageSize) {
        // 获取登录人id
        Long userId = UserHolder.getUser().getId();

        //根据登录用户id 分页查询好友
        PageBeanVo pageBeanVo = friendService.findContact(userId,pageNum,pageSize);

        //组装返回结
        List<Friend> friendList =(List<Friend>) pageBeanVo.getItems();
        //创建临时集合
        List<ContactVo> contactVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(friendList)){
            for (Friend friend : friendList) {
                //获取好友id
                Long friendId = friend.getFriendId();
                //3-2 根据好友id查询详情
                UserInfo userInfo = userInfoService.findById(friendId);
                //3-3组装ContactVo
                ContactVo contactVo = new ContactVo();

                contactVo.setUserInfo(userInfo);//复制大部分的属性
                contactVo.setUserId(friendId+"");
                //3-4 放入临时集合
                contactVoList.add(contactVo);
            }
        }
        pageBeanVo.setItems(contactVoList);
        return pageBeanVo;
    }

    //搜索附近的人
    public List<NearUserVo> findNearUser(String gender, Long distance) {
        // 获取登录人id
        Long userId = UserHolder.getUser().getId();

        //查询附近的人
        List<UserLocationVo> userLocationList =  locationService.findLocation(userId,distance);

        //封装返回结果
        List<NearUserVo> nearUserVoList = new ArrayList<>();//创建存储集合
        if(CollectionUtil.isNotEmpty(userLocationList)){
            for (UserLocationVo userLocationVo : userLocationList) {
                Long uid = userLocationVo.getUserId();//附近人的id
                UserInfo userInfo = userInfoService.findById(uid);//附近人的信息
                //排除自己
                if(userLocationVo.getUserId()==userId){
                    continue;
                }
                //排除异性
                if (!StringUtils.equals(gender,userInfo.getGender())) {
                    continue;
                }

                //封装
                NearUserVo nearUserVo = new NearUserVo();
                nearUserVo.setUserId(uid);
                nearUserVo.setAvatar(userInfo.getAvatar());
                nearUserVo.setNickname(userInfo.getNickname());
                //添加到集合中
                nearUserVoList.add(nearUserVo);
            }
        }
        //返回结果
        return nearUserVoList;
    }



}